﻿using System;
using System.Linq;
using context;
using entities;

namespace DataAccessLibrary.DAL
{
    public class AuthenDAO
    {
        private readonly BlueMDataContext _ctx;

        public AuthenDAO()
        {
            _ctx = new BlueMDataContext();
        }

        public string RoleGet(string userName, string password)
        {
            try
            {
                var query =
                    _ctx.Employees.Where(p => p.EmployeeAccount == userName && p.EmployeePassword == password).Select(
                        q => q.EmployeePosition);
                return query.FirstOrDefault();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public bool UserCheck(string userName, string passWord, string position, string serviceName)
        {
            try
            {
                var query =
                    _ctx.Employees.Where(
                        p =>
                        p.EmployeeAccount == userName && p.EmployeePassword == passWord &&
                        p.EmployeePosition == position);
                var result = query.Any();
                if (result)
                {
                    var employeeLog = new EmployeeLog
                                          {
                                              EmployeeID = query.First().EmployeeID,
                                              LoginTime = DateTime.Now,
                                              ServiceName = serviceName
                                          };
                    _ctx.EmployeeLogs.InsertOnSubmit(employeeLog);
                    _ctx.SubmitChanges();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public string ChangePassword(string userName, string passWord, string newPassWord)
        {
            try
            {
                IQueryable<Employee> query =
                   _ctx.Employees.Where(
                       p =>
                       p.EmployeeAccount == userName && p.EmployeePassword == passWord );
                if (query.Count()==1)
                {
                    Employee emp = query.First();
                    emp.EmployeePassword = newPassWord;
                   _ctx.SubmitChanges();
                    return "SUCCESS";
                }
                return "FAIL: Can not change password";
            }
            catch (Exception ex)
            {
                return "FAIL: " + ex.Message;
            }
        }


    }
}